package com.my.basics.demo.demo01;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author mars
 * @date 2025-03-25 12:39
 */
@Slf4j
public class HelloNettyServer {
    /**
     * 端口号
     */
    private final int port;

    public HelloNettyServer(int port) {
        this.port = port;
    }

    public void start() {
        try (
                // 1. 创建 Reactor 线程组
                var bossGroup = new NioEventLoopGroup();
                var workerGroup = new NioEventLoopGroup();
        ) {
            // 2. 设置 Reactor 线程组
            var bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // 设置通道类型
                    .localAddress(port) // 设置端口号
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    // 装配子通道流水线
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        // 有连接时会创建一个通道
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // 向子通道流水线添加一个 handler
                            ch.pipeline().addLast(new HelloNettyServerHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind().syncUninterruptibly();
            log.info("start server on port {}", port);
            future.channel().closeFuture().syncUninterruptibly();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // start
        new HelloNettyServer(8099).start();
    }
}
